// pages/competition/competition.js
var util = require('../../utils/util.js')
var http = require('../../utils/http.js')

var audio = wx.createInnerAudioContext();
// 在页面中定义激励视频广告
let videoAd = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    eachMoney: 0,
    trueNum: 0,
    reviveTimes: 0,
    isProgress: true,
    background: '',
    boxShadow: '',
    index: '',
    maskShow: 0,
    totalSeconds: 60,
    seconds: 12,
    songList: [],
    isClock: true,
    num: '',
    chatShow: NaN,
    interactive: [
      '你可真厉害，瑞思拜！',
      '实锤你开了听歌识曲好吗！',
      '为了车厘子自由，奥利给！',
      '确认过眼神，你是对的人！',
      '骑着我心爱的小摩托，它永远不会堵车！',
      '诶呦，不错哦，有内味了！',
      '惊不惊喜？意不意外？',
      '哼，五块钱以上的活动别叫上我！！',
      '笑容渐渐凝固！',
      '今天也是努力答题的一天！',
      '只要我跑得够慢，红包就一定会追上我！',
      '我是一个么得感情的答题机器！',
      '答题一时爽，一直答题一直爽！',
      '来啊快活啊，反正有大把时光！',
      'WOW，令人窒息的操作！',
      '答最快的题，领最大的红包！',
      '你们尽管答，超过10道题算我输！',
      '我不要你觉得，我要我觉得！',
    ],
    interTimer: '',
    countTimer: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var gameId = options.gameId;
    const data = {
      gameId: gameId
    }
    http.competition(data).then( (res) => {
      // console.log('题目信息：',JSON.parse(res.question.answerContent));
      var musicSrc = res.question.title;
      wx.setStorageSync('musicSrc',musicSrc)
      that.newContent(res);
      that.palyMusic(musicSrc);
    })
    that.interChat();
    that.autoCount();
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-96e23d22adce41d3'
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {
        if (res && res.isEnded || res === undefined) {
          console.log("我看完视频了");
          that.revive();
        } else {
          // 播放中途退出，进行提示
          wx.showToast({
            title: '观看广告时间不足，无法获得奖励',
            icon: "none",
            duration: 2000
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 播放歌曲
  palyMusic:function(musicSrc) {
    audio.loop = true;
    audio.autoplay = true;
    audio.src = musicSrc;
    audio.onPlay( () => {
      util.log('开始播放')
    });
    audio.onError( (res) => {
      util.log(res.errMsg);
      util.log(res.errCode);
    })
  },
  // 更新题目信息
  newContent: function(res) {
    var that = this;
    var songList = JSON.parse(res.question.answerContent).arr;
      wx.setStorageSync('soloResultId',res.resultId);
      console.log(songList)
      that.setData({
        songList,
      })
  },
  // 无限循环互动
  interChat: function() {
    var that = this;
    var interTimer = setInterval(() => {
      var num = Math.floor(Math.random()*18);
      that.setData({
        chatShow: true,
        num,
      })
      clearInterval(interTimer);
    },6000)
    that.interTimer  = interTimer;
    setTimeout(() => {
      that.setData({
        chatShow: 'false',
      })
      that.interChat();
    },12000)
  },
  // 选择歌曲
  choose:function(e) {
    var index = e.currentTarget.dataset.index;
    var that = this;
    clearInterval(that.countTimer);
    that.setData({
      isClock: false,
      seconds: 12,
      index,
    })
    that.nextSong(index);
    that.autoCount();
  },
  // 自动倒计时
  autoCount: function() {
    var that = this;
    var totalSeconds = that.data.totalSeconds;
    var isClock = that.data.isClock;
    var seconds = that.data.seconds;
    var countTimer = setInterval(() => {
      totalSeconds--;
      seconds--;
      if(totalSeconds === 0) {
        seconds = 0;
        clearInterval(countTimer);
      } else if(seconds == 0) {
        audio.pause();
        if(isClock == true) {
          // that.getReward();
          if(that.data.reviveTimes < 3 ) {
            // 答错弹出获得红包和提示看视频复活
            var maskShow = 1;
            } else {
              var maskShow = 2;
              // 直接请求领取奖励接口
              that.getReward();
            }
              that.setData({
                maskShow,
                isProgress: false
              })
        }
        seconds = 12;
        clearInterval(countTimer);
      }
    that.setData({
      totalSeconds,
      seconds,
    })
  }, 1000);
  that.countTimer = countTimer;
  },
  // 下一题
  nextSong: function(index) {
    var that = this;
    var correctOption = ['A',' B','C','D']
    var resultId = wx.getStorageSync('soloResultId');
    that.setData({
      isClock: true,
    })
    const data = {
      resultId: resultId,
      correctOption: correctOption[index]
    }
    //15
    http.competitionAnswer(data).then( (res) => {
      console.log('111111',res)
      var eachMoney = that.data.eachMoney;
      eachMoney = parseFloat((eachMoney + res.eachMoney/10000).toFixed(3));
      that.setData({
        eachMoney
      })
      var songList = that.data.songList;
      var trueNum = that.data.trueNum;
      trueNum++;
      songList[index].selected = true;
      var musicSrc = res.question.title;
      //正确
      wx.setStorageSync('musicSrc',musicSrc)
      that.palyMusic(musicSrc);
      that.setData({
        trueNum,
        background: 'rgba(56, 197, 32,1)',
        songList,
        boxShadow: '0rpx -10rpx 0rpx 0rpx #339b0a inset' 
      })
      setTimeout( () => {
        that.newContent(res);
      },1000)

    }, err => {
      var songList = that.data.songList;
      songList[index].selected = true;
      console.log(err)
      clearInterval(that.countTimer);
      if(that.data.reviveTimes < 3 ) {
        // 答错弹出获得红包和提示看视频复活
        var maskShow = 1;
      } else {
        var maskShow = 2;
        // 直接请求领取奖励接口
        that.getReward();
      }
      that.setData({
        maskShow,
        isProgress: false,
        background: '#e9394f',
        songList,
        boxShadow: '0rpx -10rpx 0rpx 0rpx #b61559 inset' 
      })
      audio.pause();
      //复活
      // that.revive(index);
    })
    // that.setData({
    //   songList,
    // })

  },

  // 领取奖励接口 在60s倒计时完成时调用或者三次复活后调用
  getReward: function() {
    var that = this;
    const data = {
      gameId: gameId
    }
    http.competitionReward(data).then( res => {
      var rewardMoney = res.money / 10000;
      that.setData({
        rewardMoney
      })
    })
  },
  // 复活 
  revive: function() {
    var that = this;
    var reviveTimes = that.data.reviveTimes;
    reviveTimes++;
    that.setData({
      reviveTimes,
    })
    const data = {
      gameId: gameId
    }
    //17
    http.competitionRevive(data).then( res => {
      console.log(res);
      //复活成功
      audio.play();
      // var musicSrc = wx.getStorageSync('musicSrc');
      // console.log('复活后的音乐链接',musicSrc)
      var songList = that.data.songList;
      for(var i = 0; i < songList.length; i++){
        songList[i].selected = false;
      }
      that.setData({
        songList,
        isClock: true,
        isProgress: true,
      })
      that.autoCount();
    }, err => {
      //复活失败
      console.log(err);
      that.setData({
        isClock: false,
      })
      clearInterval(that.countTimer);
    })
  },
  back:function () {
    wx.navigateBack({
      delta: 1000
    })
  },
  // 再次参赛
  again: function() {
    var that = this;
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }
    that.setData({
      maskShow: 0
    })
  },
  // 点击关闭
  clickClose: function() {
    wx.navigateBack({
      delta: 10
    })
  },
  onShareAppMessage: function() {
    var that = this;
    var userId = wx.getStorageSync("userId");
    return {
      title: '送你一个红包，快来领取吧',
      path: 'pages/index/index?userId=' + userId,
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.interTimer);
    clearInterval(that.countTimer);
    audio.pause();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.interTimer);
    clearInterval(that.countTimer);
    audio.pause();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})